package com.hzgj.bcl.soa.util;

import com.google.common.collect.Maps;

import com.hzgj.bcl.soa.net.Decoder;
import com.hzgj.bcl.soa.net.DefaultDecoder;
import com.hzgj.bcl.soa.net.DefaultEncoder;
import com.hzgj.bcl.soa.net.Encoder;
import com.hzgj.bcl.soa.rpc.message.DefaultMessageHandleFactory;
import com.hzgj.bcl.soa.spi.MessageHandleFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * Created by dell on 2015/4/3.
 */
public class ServiceLoaderUtil {

    static Map<String, MessageHandleFactory> messageBuildCache = Maps.newHashMap();

    public static Encoder getEncoder(String name) {
        ServiceLoader<Encoder> serviceLoader = ServiceLoader.load(Encoder.class);
        if (serviceLoader != null) {
            Iterator<Encoder> it = serviceLoader.iterator();
            while (it.hasNext()) {
                Encoder encoder = it.next();
                if (encoder != null && encoder.getName().equals(name)) {
                    return encoder;
                }
            }
        }
        return new DefaultEncoder();
    }

    public static Decoder getDecoder(String name) {
        ServiceLoader<Decoder> serviceLoader = ServiceLoader.load(Decoder.class);
        if (serviceLoader != null) {
            Iterator<Decoder> it = serviceLoader.iterator();
            while (it.hasNext()) {
                Decoder decoder = it.next();
                if (decoder != null && decoder.getName().equals(name)) {
                    return decoder;
                }
            }
        }
        return new DefaultDecoder();
    }

    public static <T> Iterator<T> getServiceLoaderObjects(Class<T> clazz) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz);
        return serviceLoader.iterator();
    }

    public static MessageHandleFactory getMessageBuildFactory(String name) {
        MessageHandleFactory cached = messageBuildCache.get(name);
        if (cached != null) {
            return cached;
        }
        ServiceLoader<MessageHandleFactory> serviceLoader = ServiceLoader.load(MessageHandleFactory.class);
        if (serviceLoader != null) {
            Iterator<MessageHandleFactory> it = serviceLoader.iterator();
            while (it.hasNext()) {
                MessageHandleFactory factory = it.next();
                if (factory != null && factory.getName().equals(name)) {
                    messageBuildCache.put(name, factory);
                    return factory;
                }
            }
        }
        return new DefaultMessageHandleFactory();
    }
}
